import scrapy, time
from w3lib.html import remove_tags
from kyqb_collection_spider.spiders.common import CommonSpider
from kyqb_collection_spider.items import KyqbCollectionSpiderItem


class NationaldefensemagazineSpider(CommonSpider):
    name = 'nationaldefensemagazine'
    allowed_domains = ['nationaldefensemagazine.org']
    custom_settings = {
        'ITEM_PIPELINES': {'kyqb_collection_spider.pipelines.NewImagesPipeline': 5,
                           'kyqb_collection_spider.pipelines.KyqbCollectionSpiderPipeline': 600},
    }
    start_urls = ['https://www.nationaldefensemagazine.org/articles']

    def parse(self, response):
        last_page = response.xpath('//*[@title="Last"]/@data-page').extract_first()
        for a in range(1, int(last_page)):
            href = 'https://www.nationaldefensemagazine.org/articles?PageNumber={}'.format(a)
            yield scrapy.Request(url=href, callback=self.parse_item)

    def parse_item(self, response):
        a_list = response.xpath('//*[@class="item-list results-list"]/li')
        for a in a_list:
            href = response.urljoin(a.xpath('.//a/@href').extract_first())
            if not self.redis.sismember(self.name, href):
                yield scrapy.Request(url=href, callback=self.article)
            else:
                return None

    def article(self, response):
        try:
            item = KyqbCollectionSpiderItem()
            item['data_address'] = response.url
            item['website_name'] = 'NATIONALDEFENSEMAGAZINE'
            item['spider_name'] = self.name
            item['data_source_type'] = '新闻媒体'
            item['data_type'] = 'NEWS'
            item['collection_mode'] = 'spider'
            item['collection_time'] = time.strftime('%Y-%m-%d %H:%M:%S')
            timestamp = response.xpath('//*[@class="date"]/text()').extract_first().strip()
            item['publish_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(timestamp, "%m/%d/%Y"))
            title = response.xpath('//*[@class="article-details"]/h2//text()').extract_first()
            item['title'] = remove_tags(title)
            item['abstract'] = None
            postTags = [i.strip() for i in response.xpath('//*[@class="article-details"]/p[last()]/a/text()').extract()]
            if postTags:
                item['topic'] = '!@@!'.join(postTags)
            else:
                item['topic'] = None
            ps = response.xpath('//*[@class="article-details"]|//*[@class="article-details"]/p|'
                                '//*[@class="article-details"]/p/span')
            texts = []
            for p in ps:
                containers = p.xpath('./text()').extract()
                for container in containers:
                    text = remove_tags(container).strip()
                    texts.append(text)
            item['text'] = '\n'.join(texts)
            author = response.xpath('//*[@class="author"]//text()').extract()
            if author:
                item['author'] = remove_tags(''.join(author)).replace('By', '').strip()
            else:
                item['author'] = None
            image_urls = set()
            urls = response.xpath('//*[@class="article-main-img"]//img/@src').extract()
            for url in urls:
                image_urls.add(url)
            item['image_urls'] = list(image_urls)
            yield item
        except Exception as e:
            self.logger.debug(f"采集错误:{response.url}\n{e}")
